package com.itjeffrey.autocode.filter;

import com.alibaba.fastjson.JSON;
import com.itjeffrey.autocode.common.*;
import com.itjeffrey.autocode.enums.ExceptionEnum;
import com.itjeffrey.autocode.security.JwtTokenUtil;
import com.itjeffrey.autocode.security.JwtUserDetails;
import com.itjeffrey.autocode.util.ACBaseUtil;
import com.itjeffrey.autocode.websocket.BaseSocketServer;
import com.itjeffrey.autocode.websocket.WebSocketServerContainer;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.annotation.Resource;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * JWT认证过滤器，用于拦截请求，提取jwt, 认证
 */
@Component
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {

    //过滤器日志logger
    private Logger logger = LoggerFactory.getLogger(getClass());

    @Resource
    private UserDetailsService userDetailsService;

    @Resource
    private JwtTokenUtil jwtTokenUtil;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
            throws ServletException, IOException {
        response.setContentType("application/json;charset=UTF-8");
        String ip = ACBaseUtil.getIp(request);
        logger.debug("[{}]请求路径 -> {}", ip, request.getRequestURI());
        String token = request.getHeader(jwtTokenUtil.getHeader());
        String refreshToken = request.getHeader("RefreshToken");
        //token均不为空
        if (!StringUtils.isEmpty(token) && !StringUtils.isEmpty(refreshToken)) {
            String username = jwtTokenUtil.getUsernameFromToken(token);
            String username1 = jwtTokenUtil.getUsernameFromToken(refreshToken);
            if ("-2".equals(username1)) { //refreshToken已失效
                logger.warn("RefreshToken已失效！[{}]", refreshToken);
                //532重新登录
                response.getWriter().write(JSON.toJSONString(Result.fail(532, "身份已失效，请重新登录！")));
                return;
            }
            if ("-2".equals(username)) { //accessToken已失效
                logger.warn("AccessToken已失效！[{}]", token);
                logger.debug("正在刷新AccessToken...");
                String accessToken = jwtTokenUtil.refreshAccessToken(refreshToken);
                logger.debug("AccessToken -> [{}]", accessToken);
                //将accessToken更新到tokenMap中
                BaseCommon.tokenMap.put(username1, accessToken);
                logger.debug("登录名[{}]的accessToken为[{}]", username1, BaseCommon.tokenMap.get(username1));
                //发送token给客户端
                BaseSocketServer tokenWebSocketServer = WebSocketServerContainer.getSocketServer(ip,
                        "TokenWebSocketServer");
                if (tokenWebSocketServer != null) {
                    tokenWebSocketServer.sendMessage(accessToken);
                    logger.debug("AccessToken成功发送客户端！");
                }
                return;
            }
            if ("-1".equals(username) || "-1".equals(jwtTokenUtil.getUsernameFromToken(refreshToken))) { //token声明解析失败
                response.getWriter().write(JSON.toJSONString(Result.fail(ExceptionEnum.TOKEN_CLAIMS_HANDLE_FAIL)));
                return;
            }
            logger.debug("解析登录名 -> [{}]", username);
            if (username != null && SecurityContextHolder.getContext().getAuthentication() == null) {
                UserDetails userDetails = userDetailsService.loadUserByUsername(username);
                //将用户登录信息存入上下文
                ACContext.setUserContext((JwtUserDetails) userDetails);

                if (jwtTokenUtil.validateToken(token, userDetails)) {
                    //每次请求时校验当前登录用户缓存在tokenMap中的信息是否存在，不存在提示已登出，并重新登录
                    if (!BaseCommon.tokenMap.containsKey(username) || !token.equals(BaseCommon.tokenMap.get(username)
                    )) {
                        response.getWriter().write(JSON.toJSONString(Result.fail(ExceptionEnum.ALREADY_LOGTOUT)));
                        return;
                    }
                    // 将用户信息存入 authentication，方便后续校验
                    UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken
                            (userDetails, null, userDetails.getAuthorities());
                    authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
                    // 将 authentication 存入 ThreadLocal，方便后续获取用户信息
                    SecurityContextHolder.getContext().setAuthentication(authentication);
                }
            }
        }
        chain.doFilter(request, response);
    }
}
